package com.ywx.yypicturebackend.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.utils.IOUtils;
import com.ywx.yypicturebackend.annotation.AuthCheck;
import com.ywx.yypicturebackend.common.BaseResponse;
import com.ywx.yypicturebackend.common.ResultUtils;
import com.ywx.yypicturebackend.constant.UserConstant;
import com.ywx.yypicturebackend.exception.BusinessException;
import com.ywx.yypicturebackend.exception.ErrorCode;
import com.ywx.yypicturebackend.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    CosManager cosManager;

    /**
     * 文件上传测试
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/test/upload")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<String> testUploadFile(@RequestPart MultipartFile multipartFile) {
        //文件目录
        String originalFilename = multipartFile.getOriginalFilename();
        String filePath = String.format("/test/%s", originalFilename);//占位符替换
        //创建一个临时文件
        File tempFile = null;
        try {
            //上传文件
            tempFile = File.createTempFile(filePath, "");
            multipartFile.transferTo(tempFile);
            cosManager.putObject(filePath, tempFile);
            //返回可访问的地址
            return ResultUtils.success(filePath);
        } catch (Exception e) {
            log.error("file upload error filePath: {}", filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            //删除临时文件
            if (tempFile != null) {
                boolean delete = tempFile.delete();
                if (!delete) {
                    log.error("file delete error filePath: {}", filePath);
                }
            }
        }

    }


    /**
     * 测试文件下载
     *
     * @param filePath 文件路径
     * @param response 响应对象
     */
    @GetMapping("/test/download")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public void fileDownload(String filePath, HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInputStream = null;
        try {
            COSObject cosObject = cosManager.getObject(filePath);
            //获取下载到的流
            cosObjectInputStream = cosObject.getObjectContent();

            // 获取对象元数据
            ObjectMetadata metadata = cosObject.getObjectMetadata();
            long contentLength = metadata.getContentLength();

            //处理下载到的流
            byte[] bytes = IOUtils.toByteArray(cosObjectInputStream);
            //设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
//response.setHeader("Content-Disposition", "attachment; filename=" + filePath);

            String encodedFileName = URLEncoder.encode(filePath, StandardCharsets.UTF_8.toString());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");

            response.setContentLength((int) contentLength);
            //把流写进响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();

        } catch (Exception e) {
            log.error("file download error, filepath = " + filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {

            if (cosObjectInputStream != null) {
//                关闭流
                cosObjectInputStream.close();
            }

        }


    }


}
